<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\DeviceOrder;
use app\common\model\Ground;
use app\common\model\GroundChild;
use app\common\model\MoneyLog;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;

/**
 * 示例接口
 */
class Money extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     *
     * 当前收入
     * @return void
     */
    public function current()
    {


        //查询此商家所有场地
//        $user_group = Ground::where('user_id', $this->auth->id)->column('id');
        //查询此商家所有场地
//        $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');

        $where = [];
//        $where['device_order.ground_id'] = ['in', array_merge($ground_ids, $user_group)];
        //        $where['device.user_id'] = $this->auth->id;
//            $where['device_order.createtime'] = ['between', [strtotime(date('Y-m-d')), strtotime(date('Y-m-d').' 23:59:59')]];
//        $where['device_order.is_gifts'] = 0;
        $where['device_order.status'] = 'paid';


        // 日订单数据
        $today_order_list = DeviceOrder::with('device,ground')->where($where)->whereTime('device_order.createtime', 'today')->select();
        $today_order = count($today_order_list);
        $today_income = array_reduce($today_order_list, function($carry, $item) {
            return  bcadd($carry, $item->amount, 2);
        }, 0.00);


        $month_order_list = DeviceOrder::with('device,ground')->where($where)->whereTime('device_order.createtime', 'month')->select();
        $month_order = count($month_order_list);
        $month_income = array_reduce($month_order_list, function($carry, $item) {
            return bcadd($carry, $item->amount, 2);
        }, 0.00);

        $year_order_list = DeviceOrder::with('device,ground')->where($where)->whereTime('device_order.createtime', 'year')->select();
        $year_order = count($year_order_list);
        $year_income = array_reduce($year_order_list, function($carry, $item) {
            return bcadd($carry, $item->amount, 2);
        }, 0.00);

        $this->success('success', [
            'today_order' => $today_order,
            'today_income' => (double)$today_income,
            'month_order' => $month_order,
            'month_income' => (double)$month_income,
            'year_order' => $year_order,
            'year_income' => (double)$year_income,
        ]);
    }


    /**
     * 获取最近x个月的月收入
     * @param int $months
     * @return void
     */
    public function getLastMonthsIncome()
    {

        $months = $this->request->post('months');
        if (!$months) {
            $months = 6;
        }


        $monthIncomes = [];
        for ($i = 0; $i < $months; $i++) {
            $month = date('Y-m', strtotime("-$i month"));
            $start = strtotime("$month-01 00:00:00");
            $end = strtotime("$month-01 23:59:59 +1 month -1 day");
            $order_list = DeviceOrder::where('status', '=', 'paid')
                ->whereBetween('createtime', [$start, $end])
                ->select();
            $income = array_reduce($order_list, function($carry, $item) {
                return bcadd($carry, $item->amount, 2);
            }, 0.00);;
            $monthIncomes[$month] = (double)$income;
        }

        krsort($monthIncomes); // 按月份排序

        $this->success('success', $monthIncomes);
    }


    /**
     *  总收入
     * @return void
     */
    public function getIncome()
    {
        // 获取请求的场所ID
        $ground_id = $this->request->post('ground_id');
        // 获取请求的时间段
        $period = $this->request->post('period');

        $where = [];

        if (!$ground_id) {
            //查询此商家所有场地
//            $user_group = Ground::where('user_id', $this->auth->id)->column('id');
            //查询此商家所有场地
//            $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
//            $where['device_order.ground_id'] = ['in', array_merge($ground_ids, $user_group)];
        } else {
            $where = ['device_order.ground_id' => $ground_id];
        }
        // 查询条件
//        $where['device_order.is_gifts'] = 0;
        $where['device_order.status'] = 'paid';

        // 根据时间段设置查询条件

        switch ($period) {
            case 'today':
                $where['device_order.createtime'] = ['between', [strtotime('today'), strtotime('today 23:59:59')]];
                break;
            case 'yesterday':
                $where['device_order.createtime'] = ['between', [strtotime('yesterday'), strtotime('yesterday 23:59:59')]];
                break;
            case 'week':
                $where['device_order.createtime'] = ['between', [strtotime('this week'), strtotime('this week +6 days 23:59:59')]];
                break;
            case 'month':
                $where['device_order.createtime'] = ['between', [strtotime('first day of this month'), strtotime('last day of this month 23:59:59')]];
                break;
        }

        // 查询订单数和订单总金额


        // 查询订单列表
        $order_list = DeviceOrder::with(['user', 'ground'])
            ->where($where)
            ->order('device_order.createtime', 'desc')
            ->select();
        // 计算总收入
        $total_income = array_reduce($order_list, function($carry, $item) {
            return bcadd($carry, $item->amount, 2);
        }, 0.00);
        // 返回结果
        $this->success('success', [
            'order_list' => $order_list,
            'total_income' => (double) $total_income,
        ]);
    }

    /**
     * 订单日历
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function dailyOrder()
    {
        // 获取请求的场所ID
        $ground_id = $this->request->post('ground_id');
        // 获取用户传入的年月
        $year_month = $this->request->post('year_month');
        // 检查年月格式是否正确
        if (!preg_match('/^\d{4}-\d{2}$/', $year_month)) {
            $this->error('年月格式：2024-01');
        }

        // 获取请求的时间段
        $period = $this->request->post('period');

        // 查询条件
//        $where['is_gifts'] = 0;
        $where['status'] = 'paid';

        if (!$ground_id) {
            //查询此商家所有场地
//            $user_group = Ground::where('user_id', $this->auth->id)->column('id');
//            //查询此商家所有场地
//            $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
//            $where['ground_id'] = ['in', array_merge($ground_ids, $user_group)];
        } else {
            $where = ['ground_id' => $ground_id];
        }


        // 设置年月的第一天和最后一天
        $start = strtotime("$year_month-01 00:00:00");
        $end = strtotime("$year_month-01 23:59:59 +1 month -1 day");

        // 初始化每日订单数量数组
        $daily_orders = [];
        // 获取当月所有日期
        $current_date = $start;
        while ($current_date <= $end) {
            $date_key = date('Y-m-d', $current_date);
            $daily_orders[$date_key] = 0;
            $current_date = strtotime($date_key . ' +1 day');
        }

        // 查询当月每日的订单数量
        $orders = DeviceOrder::where($where)
            ->whereBetween('createtime', [$start, $end])
            ->field('FROM_UNIXTIME(createtime, "%Y-%m-%d") as date, COUNT(*) as order_count, SUM(CAST(amount AS DECIMAL(10, 2))) as total_price')
            ->group('date')
            ->select();

        // 初始化每日订单数量和价格数组
        $daily_orders = [];
        foreach ($orders as $order) {
            $daily_orders[] = [
                'date' => $order['date'],
                'order' => $order['order_count'],
                'price' => $order['total_price']
            ];
        }

        // 返回结果
        $this->success('success', $daily_orders);

    }

    /**
     * 每月订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function monthlyOrder()
    {

        // 获取请求的场所ID
        $ground_id = $this->request->post('ground_id');

        $where = [];
        if (!$ground_id) {
//            //查询此商家所有场地
//            $user_group = Ground::where('user_id', $this->auth->id)->column('id');
//            //查询此商家所有场地
//            $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
//            $where['ground_id'] = ['in', array_merge($ground_ids, $user_group)];
        } else {
            $where = ['ground_id' => $ground_id];
        }

        // 查询所有年份每月的订单数量和订单总金额
        $monthlyData = DeviceOrder::where($where)
//            ->where('is_gifts', 0)
            ->where('status', 'paid')
            ->field('FROM_UNIXTIME(createtime, "%Y-%m") as month, COUNT(*) as order_count, SUM(CAST(amount AS DECIMAL(10, 2))) as total_amount')
            ->group('month')
            ->order('month', 'desc') // 按时间排序
            ->select();

        // 返回结果
        $this->success('success', $monthlyData);

    }


    public function getUseLog()
    {
        $ground_id = $this->request->post('ground_id');
        $device_id = $this->request->post('device_id');
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('page_size', 20);

        $where = [];

        if (!$ground_id) {
//            //查询此商家所有场地
//            $user_group = Ground::where('user_id', $this->auth->id)->column('id');
//            //查询此商家所有场地
//            $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
//            $where['device_order.ground_id'] = ['in', array_merge($ground_ids, $user_group)];
        } else {
            $where = ['device_order.ground_id' => $ground_id];
        }
        if ($device_id) {
            $where['device_order.device_id'] = $device_id;
        }
        // 查询条件
//        $where['device_order.is_gifts'] = 0;
        $where['device_order.status'] = 'paid';

        // 根据时间段设置查询条件

        if ($start_time && $end_time) {
            $where['device_order.createtime'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        } elseif ($start_time) {
            $where['device_order.createtime'] = ['>=', strtotime($start_time)];
        } elseif ($end_time) {
            $where['device_order.createtime'] = ['<=', strtotime($end_time)];
        }

        // 查询订单列表
        $order_list = DeviceOrder::with(['user', 'ground'])
            ->where($where)
            ->order('createtime', 'desc')
            ->page($page, $pageSize)
            ->select();

        // 返回查询sql
        $this->success('success', $order_list);
    }

    // 导出Excel文件
    public function downloadUseLog()
    {
        // 获取请求的场所ID
        $ground_id = $this->request->post('ground_id');
        $device_id = $this->request->post('device_id');
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');

        $where = [];

        if (!$ground_id) {
            //查询此商家所有场地
//            $user_group = Ground::where('user_id', $this->auth->id)->column('id');
//            //查询此商家所有场地

//            $where['device_order.ground_id'] = ['in', array_merge($ground_ids, $user_group)];
            $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
        } else {
            $where = ['device_order.ground_id' => $ground_id];
        }
        if ($device_id) {
            $where['device_order.device_id'] = $device_id;
        }
        // 查询条件
//        $where['device_order.is_gifts'] = 0;
        $where['device_order.status'] = 'paid';

        // 根据时间段设置查询条件

        if ($start_time && $end_time) {
            $where['device_order.createtime'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        } elseif ($start_time) {
            $where['device_order.createtime'] = ['>=', strtotime($start_time)];
        } elseif ($end_time) {
            $where['device_order.createtime'] = ['<=', strtotime($end_time)];
        }


        // 查询订单列表
        $data = DeviceOrder::with(['user', 'ground'])
            ->where($where)
            ->order('createtime', 'desc')
            ->select();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $headers = ['下单时间', '用户', '场地', '使用时间', '金额'];
        $columnIndex = 1;
        foreach ($headers as $header) {
            $sheet->setCellValueByColumnAndRow($columnIndex++, 1, $header);
        }

        // 填充数据
        $rowIndex = 2;
        foreach ($data as $order) {
            $columnIndex = 1;
            $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, date('Y-m-d H:i:s', $order['createtime'])); // 下单时间
            $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $order['user']['nickname']); // 用户名称
            $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $order['ground']['name']); // 场所名称
            $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $order['yd_time']); // 使用时间
            $sheet->setCellValueByColumnAndRow($columnIndex++, $rowIndex, $order['amount']); // 订单金额

            $rowIndex++;
        }

        // 确保目录存在
        $dir = 'exports';
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        // 保存文件
        $writer = new Xlsx($spreadsheet);
        $filePath = 'exports/order_list.xlsx';
        $writer->save($filePath);

        // 根据查询条件和当前时间戳生成文件名
        $fileName = '使用记录-' . $start_time . '~' . $end_time . '.xlsx';
        $filePath = 'exports/' . $fileName;
        $writer->save($filePath);

        // 返回文件Http下载链接
        $port = request()->port();
        if (in_array($port, [80, 443])) {
            $downloadLink = request()->domain() . '/' . $filePath;
        } else {
            $downloadLink = request()->domain() . ':' . $port . '/' . $filePath;
        }
        return $this->success('success', $downloadLink);

    }

}
